require('./config/alias');

const express = require('express');
const http = require('http');
const app = express();
const expressConf = require('./config/express');
const mysql = require('./mysql');
const router = require('./router');
const mysqlConfig = require('./config/mysql');
const config = require('./config');
const WebSocketService = require('./websocket');

// 创建 HTTP 服务器
const server = http.createServer(app);

// 初始化 WebSocket 服务
const wsService = new WebSocketService(server);

// 将 WebSocket 服务实例添加到 app 中，方便路由使用
app.locals.wsService = wsService;

router.create(app);

// 启动服务器
const startServer = () => {
    server.listen(expressConf.port, () => {
        console.log(`[HTTP] 服务器运行在端口: ${expressConf.port}`);
        console.log(`[WebSocket] WebSocket 服务运行在: ws://localhost:${expressConf.port}/ws`);
        console.log(`[WebSocket] WebSocket 测试页面: http://localhost:${expressConf.port}/websocket.html`);
    });
};

if (config.mysql) {
    let promises = [mysql.connect('mysql', mysqlConfig)];
    Promise.all(promises).then((res) => {
        startServer();
    });
} else {
    startServer();
}
